package com.teddy.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class DomUtil {
	public static String convert( Document doc) {
		StringBuilder stringBuilder = null;
		try {
		ByteArrayOutputStream stream = 
		new ByteArrayOutputStream();
		OutputFormat outputformat = new OutputFormat();
		outputformat.setIndent(4);
		outputformat.setIndenting(true);
		outputformat.setPreserveSpace(false);
		XMLSerializer serializer = new XMLSerializer();
		serializer.setOutputFormat(outputformat);
		serializer.setOutputByteStream(stream);
		serializer.asDOMSerializer();
		serializer.serialize(doc.getDocumentElement());

		stringBuilder = new StringBuilder(stream.toString());
		} catch (Exception except) {
		except.getMessage();
		}
		return stringBuilder.toString();
	}
	
	public static Document fileToXmlDoc (InputStream is) throws ParserConfigurationException, SAXException, IOException{
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setIgnoringElementContentWhitespace(true);
		DocumentBuilder builder = factory.newDocumentBuilder();

		Document doc = builder.parse(is);
		
		return doc;
	}
	
	public static Document fileToXmlDoc (String uri) throws ParserConfigurationException, SAXException, IOException{
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setIgnoringElementContentWhitespace(true);
		DocumentBuilder builder = factory.newDocumentBuilder();

		Document doc = builder.parse(uri);
		
		return doc;
	}
	
	public static Document createXMLDocument() throws ParserConfigurationException{
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setIgnoringElementContentWhitespace(true);
		DocumentBuilder builder = factory.newDocumentBuilder();
		
		return builder.newDocument();
	}
	
	public static void serializeDocument(String uri, Document doc){
		FileManager.writeFile(uri, convert(doc));
	}
}
